package storage

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/beherochuling/beesoft_api/app/helper/organization"
	"io"
	"log"
)

func NewAliyunOSS(aliyun *organization.Aliyun, bucket string) *AliyunOSS {
	client, err := oss.New(aliyun.GetEndpoint(), aliyun.GetAccessKeyId(), aliyun.GetAccessKeySecret())
	if err != nil {
		log.Fatalf("创建阿里云OSS客户端失败： %v", err)
	}
	fmt.Println("bucket", bucket, aliyun.GetEndpoint(), aliyun.GetAccessKeyId(), aliyun.GetAccessKeySecret())

	return &AliyunOSS{
		client: client,
		bucket: bucket,
	}
}
func NewAliyunOSSFromConfig(bucket string) *AliyunOSS {
	aliyun := organization.NewAliyunFromConfig()
	// provider, err := oss.NewEnvironmentVariableCredentialsProvider() // OSS_ACCESS_KEY_ID|OSS_ACCESS_KEY_SECRET
	client, err := oss.New(aliyun.GetEndpoint(), aliyun.GetAccessKeyId(), aliyun.GetAccessKeySecret()) //, oss.SetCredentialsProvider(&provider)
	if err != nil {
		log.Fatalf("创建阿里云OSS客户端失败： %v", err)
	}

	return &AliyunOSS{
		client: client,
		bucket: bucket,
	}
}

type AliyunOSS struct {
	organization organization.Aliyun // 品牌
	client       *oss.Client         // 客户端
	bucket       string              // bucket
	object       string              // object
}

// ## 属性方法

func (r *AliyunOSS) Bucket(bucket string) *AliyunOSS {
	r.bucket = bucket

	return r
}

// ## 接口方法

func (r *AliyunOSS) Upload(object string, reader io.Reader) error {
	return r.PutObject(object, reader)
}
func (r *AliyunOSS) Download(object string, writer io.Writer) error {
	return r.GetObject(object, writer)
}

// ## 封装

func (r *AliyunOSS) PutObject(object string, reader io.Reader) error {
	bucket, err := r.client.Bucket(r.bucket)
	if err != nil {
		return fmt.Errorf("获取存储桶失败： %v", err)
	}
	fmt.Println("==================")

	err = bucket.PutObject(object, reader)
	if err != nil {
		return fmt.Errorf("上传文件失败： %v", err)
	}
	return nil
}
func (r *AliyunOSS) PutObjectFromFile(object string, localFilePath string) error {
	bucket, err := r.client.Bucket(r.bucket)
	if err != nil {
		return fmt.Errorf("获取存储桶失败： %v", err)
	}

	err = bucket.PutObjectFromFile(object, localFilePath)
	if err != nil {
		return fmt.Errorf("上传文件失败： %v", err)
	}
	return nil
}
func (r *AliyunOSS) GetObject(object string, writer io.Writer) error {
	bucket, err := r.client.Bucket(r.bucket)
	if err != nil {
		return fmt.Errorf("获取存储桶失败： %v", err)
	}
	_, err = bucket.GetObject(object)
	if err != nil {
		return fmt.Errorf("下载文件失败： %v", err)
	}

	return nil
}
func (r *AliyunOSS) GetObjectToFile(object string, localFilePath string) error {
	bucket, err := r.client.Bucket(r.bucket)
	if err != nil {
		return fmt.Errorf("获取存储桶失败： %v", err)
	}
	err = bucket.GetObjectToFile(object, localFilePath)
	if err != nil {
		return fmt.Errorf("下载文件失败： %v", err)
	}

	return nil
}
